<?php

declare(strict_types=1);

namespace app\chat\controller\admin;

use think\Request;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use app\chat\model\Question as ChatQuestion;
use think\facade\Db;

class Question extends Backend
{
    public function initialize()
    {
        $this->model = new ChatQuestion;
    }

    /**
     * 猜你想问列表
     *
     * @return \think\Response
     */
    public function list()
    {
        $questions = $this->model->sheepFilter()->paginate(request()->param('list_rows', 10));
        return success('获取成功', $questions);
    }


    /**
     * 猜你想问添加
     *
     * @return \think\Response
     */
    public function add(Request $request)
    {
        $params = $this->request->only(['room_id', 'title', 'status', 'weigh']);
        $params['content'] = $request->param('content', '', null);      // content 不经过全局过滤
        $this->svalidate($params, ".add");

        $data = Db::transaction(function () use ($params) {
            $this->model->save($params);
        });
        return success('保存成功', $data);
    }



    /**
     * 猜你想问详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $question = $this->model->findOrFail($id);

        return success('获取成功', $question);
    }



    /**
     * 猜你想问编辑
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit(Request $request, $id)
    {
        $params = $this->request->only(['room_id', 'title', 'status', 'weigh']);
        $request->has('content') && $params['content'] = $request->param('content', '', null);      // content 不经过全局过滤
        $this->svalidate($params);

        $id = explode(',', $id);

        Db::transaction(function () use ($id, $params) {
            foreach ($this->model->whereIn('id', $id)->cursor() as $question) {
                $question->save($params);
            }
        });

        return success('更新成功');
    }


    /**
     * 删除猜你想问
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $id = explode(',', $id);

        Db::transaction(function () use ($id) {
            foreach ($this->model->whereIn('id', $id)->cursor() as $question) {
                $question->delete();
            }
        });

        return success('删除成功');
    }
}
